﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using JohnnySins.DAL.Repositories;
using JohnnySins.Entities;

namespace JohnnySins
{
    public partial class Join : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Redirect("~/Default.aspx");

            try
            {

                //Label12.Text = Context.Request.Url.Scheme + "  " + Context.Request.Url.Host + " " +Context.Request.Url.AbsolutePath;
                //Label13.Text = Context.Request.UrlReferrer!=null?Context.Request.UrlReferrer.Scheme+ "  " + Context.Request.UrlReferrer.Host + " " +Context.Request.UrlReferrer.AbsolutePath:"";

                //if (Context.Request.UserHostAddress == "174.129.249.162"
                //    || Context.Request.UserHostAddress == "65.17.248."
                //    || Context.Request.UserHostAddress == "68.71.103."
                //    || Context.Request.UserHostAddress == "184.73.155.222"
                //    || Context.Request.UserHostAddress == "184.72.56.152"
                //    || Context.Request.UserHostAddress == "184.72.56.199"
                //    || Context.Request.UserHostAddress == "184.73.192.230")
                //{
                //    Label10.Text = Context.Request.UserHostAddress; 
                //    Label11.Text = "IP соответствует";
                //}
                //else
                //{
                //    Label10.Text = Context.Request.UserHostAddress; 
                //    Label11.Text = "IP НЕ соответствует";
                //}

                eventMessage.Text = Request.QueryString["ans"];//YGOODTEST|1630067808
                stackTrace.Text = Request.QueryString["country"];//RU
                path.Text = Request.QueryString["password"];//asdasd
                queryString.Text = Request.QueryString["name"]; //Moura
                browser.Text = Request.QueryString["email"];//asdasd@gmail.com
                userHostAddress.Text = Context.Request.UserHostAddress; //ciirjj2p467146
                urlReferrer.Text = Request.QueryString["zip"]; //11111

                //string ans = "YGOODTESTY|1630067808";// !String.IsNullOrEmpty(Request.QueryString["ans"])?Request.QueryString["ans"]:Strinr.Empty;
                //string country = "RU";//Request.QueryString["country"]
                //string password ="asdasd" ;//Request.QueryString["password"]
                //string name = "Moura"; //Request.QueryString["name"]
                //string email = "asdasd@gmail.com";//Request.QueryString["email"]
                //string pi_code = "ciirjj2p467146"; //Request.QueryString["pi_code"]
                //string zip = "11111"; //Request.QueryString["zip"]

                string ans = !String.IsNullOrEmpty(Request.QueryString["ans"]) ? Request.QueryString["ans"] : String.Empty;
                string country = !String.IsNullOrEmpty(Request.QueryString["country"]) ? Request.QueryString["country"] : String.Empty;
                string name = !String.IsNullOrEmpty(Request.QueryString["name"]) ? Request.QueryString["name"] : String.Empty;
                string username = !String.IsNullOrEmpty(Request.QueryString["username"]) ? Request.QueryString["username"] : String.Empty;
                string password = !String.IsNullOrEmpty(Request.QueryString["password"]) ? Request.QueryString["password"] : String.Empty;
                string email = !String.IsNullOrEmpty(Request.QueryString["email"]) ? Request.QueryString["email"] : String.Empty;
                string pi_code = !String.IsNullOrEmpty(Request.QueryString["pi_code"]) ? Request.QueryString["pi_code"] : String.Empty;
                string zip = !String.IsNullOrEmpty(Request.QueryString["zip"]) ? Request.QueryString["zip"] : String.Empty;

                //If User Exist

                string userName = Membership.GetUserNameByEmail(email);

                try
                {
                    if (!String.IsNullOrEmpty(userName))
                    {
                        var cookie = new HttpCookie("email", String.Empty);
                        cookie.Expires = DateTime.Now.AddYears(1);
                        Response.Cookies.Add(cookie);

                        FormsAuthentication.SetAuthCookie(userName, false);


                        Response.Redirect("~/member/Home.aspx");
                    }
                }
                catch (Exception ex)
                {
                    stackTrace.Text = "Redirect('~/member/Home.aspx'); не произошел";
                    path.Text = "ошибка редиректа ~/member/Home.aspx: " + ex.Message + "   " + ex.Data;
                }
                

                //User Register

                bool isUserRegister = false;

                if (!String.IsNullOrEmpty(ans) && ans.IndexOf("Y") == 0)  // TODO: check status  ans=[STATUS][APPROVE/DENY CODE]  STATUS: a one letter code with value Y (transaction approved) or N (denied). &ans=YGOODTEST%7c1629972669";
                {
                    List<Country> countryList;
                    using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
                    {
                        countryList = repo.CountryCombo(true, false).ToList();
                    }

                    var queryCountry = country;
                    var countryCurr = countryList.FirstOrDefault(x => x.CountryName == queryCountry);

                    using (var repo = RepositoryFactory.ResolveRepository<UserRepository>())
                    {
                        User usr = new User();
                        usr.LastName = "";
                        usr.FirstName = name;
                        usr.Email = email;
                        usr.UserName = username;
                        usr.Password = password;
                        usr.Zip = zip;
                        usr.CountryId = countryList.Count > 0 && countryCurr != null ? countryCurr.CountryId : -1;

                        if (pi_code == "ciirjj2p467145") //1 month  
                        {
                            usr.PaymentTypeId = 2;
                        }
                        else if (pi_code == "ciirjj2p467146") //3 month  
                        {
                            usr.PaymentTypeId = 3;
                        }
                        else if (pi_code == "ciirjj3p531975") //12 month  
                        {
                            usr.PaymentTypeId = 4;
                        }
                        else
                        {
                            usr.PaymentTypeId = 1; //trial registration 
                        }

                        repo.AddManual(usr, usr.Password);

                        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Alert", string.Format("alert('{0}');", "You registered successfully!"), true);

                    }

                    isUserRegister = true;

                }
                    
                //Save Log user registration 
                string eventMessageLog = ans;
                string stackTraceLog = Environment.StackTrace;
                string currentUserLog = email;
                string pathLog = Context.Request.Path.Replace("'", "''");
                string queryStringLog = Context.Request.QueryString.ToString();
                string browserLog = Context.Request.Browser.Browser;
                string userHostAddressLog = Context.Request.UserHostAddress;
                string urlReferrerLog = (Context.Request.UrlReferrer != null ? Context.Request.UrlReferrer.ToString() : "");

                using (var repos = RepositoryFactory.ResolveRepository<LogRepository>())
                {
                    repos.RegisterUserLog(eventMessageLog, stackTraceLog, currentUserLog, pathLog, queryStringLog, browserLog,
                        userHostAddressLog, urlReferrerLog);
                }

                if (isUserRegister)
                {
                    Response.Redirect("~/Default.aspx");
                    //Response.Redirect("~/member/Home.aspx");
                }
                else
                {
                    Response.Redirect("~/Default.aspx");
                }

                //try
                //{
                //    Response.Redirect("~/member/Home.aspx");
                //}
                //catch (Exception ex)
                //{
                //    queryString.Text = "Redirect('~/member/Home.aspx') после записи в лог не произошел";
                //    browser.Text = "ошибка редиректа ~/member/Home.aspx: " + ex.Message + "   " + ex.Data;
                //}
                
            }
            catch (Exception ex)
            {
                Error.Text = ex.Message + "   " + ex.Data;
               // Response.Redirect("~/Default.aspx");
            }

            
        }
    }
}